package health

import (
	"context"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center-client/service/discover"
	"github.com/go-redis/redis/v8"
	"math/rand"
	"time"
)

func CheckHealth() {
	retry(func() bool {
		var redisClient *redis.Client
		defer func() {
			if redisClient != nil {
				redisClient.Close()
			}
			_ = recover()
		}()
		instances := discover.GetDiscoverClientManager().GetServiceInfo("redis-service")
		if instances == nil || len(instances) == 0 {
			return false
		}
		instance := instances[rand.Intn(len(instances))]

		if instance.Endpoints == nil || len(instance.Endpoints) == 0 {
			return false
		}
		addr := instance.Endpoints[0]
		redisClient = redis.NewClient(&redis.Options{
			Addr:     addr, // Redis服务器地址
			Username: "root",
			Password: "123456", // 无密码（如有密码需填写）
			DB:       0,        // 默认数据库0

			MaxRetries:   3,
			DialTimeout:  5 * time.Second,
			ReadTimeout:  10 * time.Second,
			WriteTimeout: 5 * time.Second,

			PoolSize:     30,
			MinIdleConns: 5,
			IdleTimeout:  30 * time.Second,
		})
		if redisClient == nil {
			return false
		}
		_, err := redisClient.Ping(context.Background()).Result()
		if err == nil {
			return true
		}
		return false
	}, 5)
}

func retry(function func() bool, dy int) bool {
	for {
		if function() {
			return true
		}
		logger.Error("redis is not health")
		time.Sleep(time.Duration(dy) * time.Second)
	}
}
